"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 备机事务内写转发
Case Name   : 备机在事务中执行读写操作，提交
Create At   : 2023/07/03
Owner       : opentestcase033
Description :
    1.修改enable_remote_execute参数值为on
    2.创建表
    3.备机开启事务向表中插入数据并查询，主机查询后提交
    4.主机查询表数据
    5.备机查看日志打印
    6.清理环境
Expect      :
    1.修改成功
    2.创建成功
    3.执行成功，5条数据
    4.无数据
    5.日志记录建立连接、转发给主机、接受执行结果等libpqsw信息
    6.成功
History     :
    modified: 2025/03/05 modified by kyleze,参数值变化,优化用例
"""

import os
import time
import unittest

from yat.test import Node
from yat.test import macro
from testcase.utils.Logger import Logger
from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.ComThread import ComThread


class MultiNodeWrite(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f"-----{os.path.basename(__file__)} start-----")
        self.pri_sh = CommonSH('PrimaryDbUser')
        self.std_sh = CommonSH('Standby1DbUser')
        self.std_node = Node('Standby1DbUser')
        self.common = Common('Standby1DbUser')
        self.constant = Constant()
        self.tb_name = 't_multi_node_write_0001'
        self.new_log_dir = os.path.join(
            macro.PG_LOG_PATH, 'pg_log_multi_node_write0001')
        self.enable_remote_execute = 'enable_remote_execute'
        self.log_statement = 'log_statement'
        self.log_directory = 'log_directory'
        self.remote_excute_default = self.common.show_param(
            self.enable_remote_execute)
        self.log_statement_default = self.common.show_param(self.log_statement)
        self.log_dir_default = self.common.show_param(self.log_directory)
        shell_cmd = f"rm -rf {self.new_log_dir}"
        self.log.info(shell_cmd)
        shell_msg = self.common.get_sh_result(self.std_node, shell_cmd)
        self.assertEquals('', shell_msg, '删除目录失败')

    def test_multi_node_write(self):
        step1 = "-----step1:修改enable_remote_execute参数值为on;expect:修改成功-----"
        self.log.info(step1)
        result = self.std_sh.execute_gsguc(
            'set', self.constant.GSGUC_SUCCESS_MSG,
            f'{self.enable_remote_execute}=on')
        self.assertTrue(result, f'执行失败:{step1}')
        restart_res = self.std_sh.restart_db_cluster()
        self.assertTrue(restart_res, f'执行失败:{step1}')
        show_remote_excute = self.common.show_param(self.enable_remote_execute)
        self.assertEquals(show_remote_excute, 'on', f'执行失败:{step1}')
        result = self.std_sh.execute_gsguc(
            'reload', self.constant.GSGUC_SUCCESS_MSG,
            f'{self.log_statement}=all')
        self.assertTrue(result, f'执行失败:{step1}')
        result = self.std_sh.execute_gsguc(
            'reload', self.constant.GSGUC_SUCCESS_MSG,
            f"{self.log_directory}='{self.new_log_dir}'", single=True)
        self.assertTrue(result, f'执行失败:{step1}')

        step2 = "-----step2:主机创建测试表;expect:创建成功-----"
        self.log.info(step2)
        create_tb = f'''drop table if exists {self.tb_name} cascade;
        create table {self.tb_name}(id int) with(segment = on);'''
        create_res = self.pri_sh.execut_db_sql(create_tb)
        self.log.info(create_res)
        self.assertIn(self.constant.CREATE_TABLE_SUCCESS, create_res,
                      f'执行失败:{step2}')

        step3 = "-----step3:备机在事务中执行读写;expect:执行成功-----"
        self.log.info(step3)
        sql_cmd = f'''start transaction;
        insert into {self.tb_name} values(generate_series(1,10));
        delete from {self.tb_name} where id > 5;
        select * from {self.tb_name};
        select pg_sleep(4);
        commit;'''
        session1 = ComThread(self.std_sh.execut_db_sql, args=(sql_cmd,))
        session1.setDaemon(True)
        session1.start()
        time.sleep(2)

        step4 = "-----step4:主机查询表数据;expect:成功 5-----"
        self.log.info(step4)
        sql = f"select * from {self.tb_name};" \
              f"select pg_sleep(3);" \
              f"select count(*) from {self.tb_name};"
        session2 = ComThread(self.pri_sh.execut_db_sql, args=(sql,))
        session2.setDaemon(True)
        session2.start()
        session1.join(15)
        session2.join(15)
        res1 = session1.get_result()
        self.log.info(f'session1_results:\n {res1}')
        res2 = session2.get_result()
        self.log.info(f'session2_results:\n {res2}')
        self.assertIn(self.constant.START_TRANSACTION_SUCCESS_MSG,
                      res1, f'执行失败:{step3}')
        self.assertIn(self.constant.INSERT_SUCCESS_MSG, res1, f'执行失败:{step3}')
        self.assertIn(self.constant.DELETE_SUCCESS_MSG, res1, f'执行失败:{step3}')
        self.assertIn("(5 rows)", res1, f'执行失败:{step3}')
        self.assertIn(self.constant.COMMIT_SUCCESS_MSG, res1, f'执行失败:{step3}')
        self.assertIn('0 rows', res2.splitlines()[2], f'执行失败:{step4}')
        self.assertEqual(res2.splitlines()[-2].strip(), '5', f'执行失败:{step4}')

        step5 = "-----step5:备机查看日志打印;expect:日志记录建立连接、" \
                "转发给主机、接受执行结果等libpqsw信息-----"
        self.log.info(step5)
        cmd = f"ls -t {self.new_log_dir}"
        self.log.info(cmd)
        cmd_res = self.common.get_sh_result(self.std_node, cmd)
        logfile = os.path.join(self.new_log_dir, cmd_res.split()[-1])
        self.log.info(logfile)
        cmd = f"cat {logfile}"
        self.log.info(cmd)
        cmd_res = self.common.get_sh_result(self.std_node, cmd)
        self.log.info(cmd_res)
        self.assertIn('libpq send sql at my side as well:START TRANSACTION',
                      cmd_res, f'执行失败:{step5}')
        self.assertEqual(cmd_res.count('we find new local-only execute '
                                       'sql by query_list:SELECT'), 2,
                         f'执行失败:{step5}')
        self.assertIn('we find new transfer request:[TRACE] Q: portal=INSERT',
                      cmd_res, f'执行失败:{step5}')
        self.assertIn('we find new transfer request:[TRACE] Q: portal=DELETE',
                      cmd_res, f'执行失败:{step5}')
        self.assertIn('libpq send sql at my side as well:COMMIT',
                      cmd_res, f'执行失败:{step5}')

    def tearDown(self):
        step6 = "-----step6:环境清理，恢复参数;expect:成功-----"
        self.log.info(step6)
        drop_tb = f"drop table {self.tb_name};"
        drop_res = self.std_sh.execut_db_sql(drop_tb)
        self.log.info(drop_res)
        result1 = self.std_sh.execute_gsguc(
            'set', self.constant.GSGUC_SUCCESS_MSG,
            f'{self.enable_remote_execute}={self.remote_excute_default}')
        restart_res = self.std_sh.restart_db_cluster()
        self.log.info(restart_res)
        result2 = self.std_sh.execute_gsguc(
            'reload', self.constant.GSGUC_SUCCESS_MSG,
            f'{self.log_statement}={self.log_statement_default}')
        result3 = self.std_sh.execute_gsguc(
            'reload', self.constant.GSGUC_SUCCESS_MSG,
            f"{self.log_directory}='{self.log_dir_default}'", single=True)
        show_remote_excute = self.common.show_param(self.enable_remote_execute)
        show_log_statement = self.common.show_param(self.log_statement)
        show_log_dir = self.common.show_param(self.log_directory)
        self.assertIn(self.constant.TABLE_DROP_SUCCESS, drop_res,
                      f'执行失败:{step6}')
        self.assertTrue(result1 and result2 and result3, f'执行失败:{step6}')
        self.assertTrue(restart_res, f'执行失败:{step6}')
        self.assertEquals(show_remote_excute, self.remote_excute_default,
                          f'执行失败:{step6}')
        self.assertEquals(show_log_statement, self.log_statement_default,
                          f'执行失败:{step6}')
        self.assertEquals(show_log_dir, self.log_dir_default,
                          f'执行失败:{step6}')
        self.log.info(f"-----{os.path.basename(__file__)} end-----")
